// 搜索页面

<template>
  <div class="search">
    <!-- 头部模块 -->
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search placeholder="请输入搜索关键词" shape="round" />
      <span @click="onSearch">搜索</span>
    </div>
    <!-- 历史记录 -->
    <div class="historyList">
      <h2>历史记录</h2>
      <p v-for="(v,i) in historyList" :key="i" @click="onSearch(v)">{{v}}</p>
    </div>
    <!-- 搜索记录 -->
    <div class="searchList">
      <h2>搜索记录</h2>
      <router-link
        v-for="value in searchList"
        :key="value.id"
        :to="'/articleDetail/'+value.id"
      >{{value.title}}</router-link>
    </div>
  </div>
</template>

<script>
// 引入api
import { searchArticle } from "@/apis/articles";
export default {
  data() {
    return {
      userKey: "",
      historyList: [],
      searchList: [],
    };
  },
  mounted() {
    // 先获取历史记录
    this.historyList =
      JSON.parse(localStorage.getItem("hm_toutiao_search_history_52")) || [];
  },
  methods: {
    // key 可能有，可能没有
    async onSearch(key) {
      console.log(key, typeof key);
      if (key && typeof key != "object" && key.trim()) {
        this.userKey = key;
      }
      // 向服务器请求数据
      let res = await searchArticle(this.userKey);
      console.log(res);
      this.searchList = res.data.data;
      // 搜索历史不止一个，允许用户存储多个关键字，所以它的本质应该是一个数组
      console.log(this.userKey);
      let arr =
        JSON.parse(localStorage.getItem("hm_toutiao_search_history_52")) || [];
      arr.unshift(this.userKey);
      console.log(arr);
      // 对搜索过的词存储在历史记录本地存储
      localStorage.setItem("hm_toutiao_search_history_52", JSON.stringify(arr));
      // 将本次的关键字添加到历史记录
      this.historyList.unshift(this.userKey);
    },
  },
};
</script>

<style lang="less" scoped>
.header {
  padding: 0 10px;
  height: 44px;
  display: flex;
  align-items: center;
  span {
    width: 50px;
  }
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.historyList,
.searchList {
  margin: 0 10px;
  padding: 10px 0;
  h2 {
    font-weight: 700;
    font-size: 18px;
    line-height: 30px;
    color: #000;
  }
  > a {
    text-decoration: none;
    color: #333;
    word-break: keep-all;
    /* 1. 文字显示不开，是否开启换行   nowrap：不换行*/
    white-space: nowrap;
    /* 2. 超出的隐藏 */
    overflow: hidden;
    /* 3. 文字溢出的时候，用省略号显示 */
    text-overflow: ellipsis;
  }
}
.historyList {
  border-bottom: 1px solid #ccc;
}
</style>